package com.gds.wiki.cloud.orderCenter.server.oauth2.core.service;

import com.gds.wiki.cloud.oauth2.common.integration.IntegrationAuthentication;
import com.gds.wiki.cloud.oauth2.common.integration.IntegrationAuthenticationContext;
import com.gds.wiki.cloud.oauth2.common.integration.authenticator.IntegrationAuthenticator;
import com.gds.wiki.cloud.oauth2.common.model.SecurityMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 集成认证用户服务
 *
 * @author WIKI
 * @date 2018-3-7
 **/
@Service
public class IntegrationUserDetailsService implements UserDetailsService {

    private List<IntegrationAuthenticator> authenticators;


    @Autowired(required = false)
    public void setIntegrationAuthenticators(List<IntegrationAuthenticator> authenticators) {
        this.authenticators = authenticators;
    }

    @Override
    public SecurityMember loadUserByUsername(String username) throws UsernameNotFoundException {
        IntegrationAuthentication integrationAuthentication = IntegrationAuthenticationContext.get();
        //判断是否是集成登录
        if (integrationAuthentication == null) {
            integrationAuthentication = new IntegrationAuthentication();
        }
           integrationAuthentication.setUsername(username);

        SecurityMember securityMember= (SecurityMember) this.authenticate(integrationAuthentication);
            if(securityMember == null){
                throw new UsernameNotFoundException("用户名："+username+"不存在");
            }
            Collection<GrantedAuthority> authorities = new ArrayList<>();
//            roleApi.findUserRoleByUid(securityUser.getId()).forEach((Map roleList)->{
//                GrantedAuthority authority = new SimpleGrantedAuthority((String) roleList.get("name"));
//                authorities.add(authority);
//            });
//            authorities.add(new SimpleGrantedAuthority("gds-user"));
//            securityUser.setGrantList(authorities);
//            securityUser.setResourceList(resourceApi.findUserResourceByUid(securityUser.getId()));
            return securityMember;
    }

    private SecurityMember authenticate(IntegrationAuthentication integrationAuthentication) {
        if (this.authenticators != null) {
            for (IntegrationAuthenticator authenticator : authenticators) {
                if (authenticator.support(integrationAuthentication)) {
                    return (SecurityMember) authenticator.authenticate(integrationAuthentication);
                }
            }
        }
        return null;
    }
}
